from flask import Flask, redirect, url_for, request,Response,render_template,send_file
from flask_cors import CORS
from picamera import PiCamera
import json
import pwm
import time

#建立flask app
app=Flask(__name__)
#建立小车对象
car=pwm.CarMove()

#将响应函数关联到网络地址
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/smartcar/control',methods=['POST'])
def car_control():
    #加载前端传回的json数据，转换成字典类型
    dic=json.loads(request.get_data())
    #将字典中的参数分别提取出来以供函数调用
    speed=int(dic['speed'])
    theta=int(dic['theta'])
    print(speed,theta)
    pwm.control(speed,theta,car)
    return json.dumps(dic)

@app.route('/smartcar/stop',methods=['POST'])
def car_stop():
    pwm.stop(car)
    return request.get_data() 

@app.route('/run',methods=['POST'])
def run():
    pwm.control(50,90,car)
    return request.get_data()


if __name__ == "__main__":
    #允许跨域访问
    CORS(app,resources=r'/*')
    app.run(host='0.0.0.0',threaded=True,debug=True)
